package com.wushi.lenovo.asia5b.app_ui.credit.fragment;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.ListPopupWindow;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.permissions.RxPermissions;
import com.mvp.base.BaseAppCompatActivity;
import com.mvp.base.BaseMvpFragment;
import com.mvp.base.model.ResultModel;
import com.mvp.helper.TimePickerHelper;
import com.mvp.utils.InputMethodUtils;
import com.mvp.utils.StringUtils;
import com.mvp.utils.ToastUtil;
import com.mvp.utils.https.MapHelper;
import com.wushi.lenovo.asia5b.R;
import com.wushi.lenovo.asia5b.app_di.APPComponentFactory;
import com.wushi.lenovo.asia5b.app_di.credit.mvpview.AtmFragmentView;
import com.wushi.lenovo.asia5b.app_di.credit.presenter.AtmFragmentPresenter;
import com.wushi.lenovo.asia5b.app_event.TopupEvent;
import com.wushi.lenovo.asia5b.app_model.credit.BankModel;
import com.wushi.lenovo.asia5b.app_model.credit.WithdrawBankModel;
import com.wushi.lenovo.asia5b.app_model.other.UserInfo;
import com.wushi.lenovo.asia5b.app_utils.WTimeUtils;
import com.wushi.lenovo.asia5b.app_utils.eye.EyeUtils;
import com.wushi.lenovo.asia5b.app_utils.eye.PopupListAdapter;
import com.wushi.lenovo.asia5b.app_utils.eye.PopupWindowHelper;
import com.wushi.lenovo.asia5b.app_utils.helper.CacheHelper;
import com.wushi.lenovo.asia5b.app_widget.ErrorTextView;

import org.greenrobot.eventbus.EventBus;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

import static timber.log.Timber.d;

/**
 * Created by zhangyuncai on 2019/1/15.
 */
public class AtmFragment extends BaseMvpFragment<AtmFragmentView, AtmFragmentPresenter>
        implements AtmFragmentView {
    @BindView(R.id.et_atm_amount)
    EditText et_atm_amount;
    @BindView(R.id.tv_atm_amount_error)
    ErrorTextView tv_atm_amount_error;
    @BindView(R.id.et_atm_phonenumber)
    EditText et_atm_phonenumber;
    @BindView(R.id.tv_atm_phonenumber_error)
    ErrorTextView tv_atm_phonenumber_error;
    @BindView(R.id.ll_atm_bank)
    LinearLayout ll_atm_bank;
    @BindView(R.id.tv_atm_selectbank)
    TextView tv_atm_selectbank;
    @BindView(R.id.tv_atm_selectbank_error)
    TextView tv_atm_selectbank_error;
    @BindView(R.id.et_atm_referenceno)
    EditText et_atm_referenceno;
    @BindView(R.id.tv_atm_referenceno_error)
    ErrorTextView tv_atm_referenceno_error;
    @BindView(R.id.tv_atm_hour_error)
    TextView tv_atm_hour_error;
    @BindView(R.id.tv_atm_year_error)
    TextView tv_atm_year_error;
    @BindView(R.id.et_atm_remark)
    EditText et_atm_remark;
    @BindView(R.id.et_atm_nofilechosen)
    EditText et_atm_nofilechosen;
    @BindView(R.id.tv_atm_nofilechosen_error)
    ErrorTextView tv_atm_nofilechosen_error;
    @BindView(R.id.bt_atm_submit)
    Button bt_atm_submit;
    @BindView(R.id.tv_atm_dd)
    TextView tv_atm_dd;
    @BindView(R.id.tv_atm_mm)
    TextView tv_atm_mm;
    @BindView(R.id.tv_atm_yyyy)
    TextView tv_atm_yyyy;
    @BindView(R.id.tv_atm_hh)
    TextView tv_atm_hh;
    @BindView(R.id.tv_atm_minute)
    TextView tv_atm_minute;
    @BindView(R.id.tv_atm_ss)
    TextView tv_atm_ss;
    @BindView(R.id.ll_atm_time_hour)
    LinearLayout ll_atm_time_hour;

    private PopupListAdapter<BankModel> bankAdapter;
    private ListPopupWindow popupWindowBank;
    private Date selectDate;//年月日+时分秒
    private Date yearDate;//年月日
    private Date hourDate;//时分秒
    private TimePickerView yearTimePickerDialog;
    private TimePickerView hourTimePickerDialog;

    @Override
    protected void constructComponent() {
        APPComponentFactory.getAppBaseComponent().inject(this);
    }

    @Override
    protected int getLayout() {
        return R.layout.fragment_atm2;
    }

    public Date getSelectDate() {
        if (yearDate == null || hourDate == null) {
            return null;
        }
        Calendar selectCalendar = Calendar.getInstance();
        Calendar yearCalendar = Calendar.getInstance();
        yearCalendar.setTime(yearDate);
        Calendar hourCalendar = Calendar.getInstance();
        hourCalendar.setTime(hourDate);
        selectCalendar.set(Calendar.YEAR, yearCalendar.get(Calendar.YEAR));
        selectCalendar.set(Calendar.MONTH, yearCalendar.get(Calendar.MONTH));
        selectCalendar.set(Calendar.DAY_OF_MONTH, yearCalendar.get(Calendar.DAY_OF_MONTH));
        selectCalendar.set(Calendar.HOUR_OF_DAY, hourCalendar.get(Calendar.HOUR_OF_DAY));
        selectCalendar.set(Calendar.MINUTE, hourCalendar.get(Calendar.MINUTE));
        selectCalendar.set(Calendar.SECOND, hourCalendar.get(Calendar.SECOND));
        selectDate = selectCalendar.getTime();
        return selectDate;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
        initEvent();
    }


    @Override
    protected void lazyFetchData() {
        initData();
    }

    @Override
    protected void initView() {

        et_atm_amount.setHint(String.format(getString(R.string.topup_notice_min), CacheHelper.loadCreditMinByLocal().getAtm_onlineBanking_minimum_value()));

        bankAdapter = new PopupListAdapter<>(getContext(), R.layout.item_popupitem_withdraw_adapter);
        popupWindowBank = PopupWindowHelper.getListPopupWindow(getContext(), bankAdapter
                , tv_atm_selectbank, ListPopupWindow.WRAP_CONTENT);
    }

    private void showHourDialog() {

        Calendar currentDate = Calendar.getInstance();
        if (hourDate != null) {
            currentDate.setTime(hourDate);
        }
        if (hourTimePickerDialog == null) {
            boolean[] timeType = new boolean[]{false, false, false, true, true, true};
            hourTimePickerDialog = TimePickerHelper.getInstance().getTimePickerDialog(getContext(), null, null, null, currentDate, timeType, new OnTimeSelectListener() {
                @Override
                public void onTimeSelect(Date date, View v) {
                    hourDate = date;
                    Calendar resultCalendar = Calendar.getInstance();
                    tv_atm_hour_error.setVisibility(View.GONE);
                    setTimeView();

                }
            });
        }
        hourTimePickerDialog.setDate(currentDate);
        hourTimePickerDialog.show();
    }

    private void showYearDialog() {
        Calendar startDate = Calendar.getInstance();
        startDate.add(Calendar.YEAR, -20);
        Calendar endDate = Calendar.getInstance();
        Calendar currentDate = Calendar.getInstance();
        if (yearDate != null) {
            currentDate.setTime(yearDate);
        }
        if (yearTimePickerDialog == null) {
            boolean[] timeType = new boolean[]{true, true, true, false, false, false};
            yearTimePickerDialog = TimePickerHelper.getInstance().getTimePickerDialog(getContext(), null, startDate, endDate, currentDate, timeType, new OnTimeSelectListener() {
                @Override
                public void onTimeSelect(Date date, View v) {

                    yearDate = date;
                    tv_atm_year_error.setVisibility(View.GONE);
                    setTimeView();
                }
            });
        }
        yearTimePickerDialog.setDate(currentDate);
        yearTimePickerDialog.show();
    }

    private void setTimeView() {
        if (yearDate != null) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(yearDate);
            d("--->>>>>>>>---选择的年月日时间:" + calendar.toString());
            int day = calendar.get(Calendar.DAY_OF_MONTH);
            int month = calendar.get(Calendar.MONTH) + 1;
            int year = calendar.get(Calendar.YEAR);
            tv_atm_dd.setText(day + "");
            tv_atm_mm.setText(month + "");
            tv_atm_yyyy.setText(year + "");
        }
        if (hourDate != null) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(hourDate);
            d("--->>>>>>>>---选择的时分秒时间:" + calendar.toString());
            int hour = calendar.get(Calendar.HOUR_OF_DAY);
            int minute = calendar.get(Calendar.MINUTE);
            int second = calendar.get(Calendar.SECOND);
            tv_atm_hh.setText(hour + "");
            tv_atm_minute.setText(minute + "");
            tv_atm_ss.setText(second + "");
        }
    }

    @Override
    protected void initData() {
//        getPresenter().getToBanks();
    }

    private void submit() {
//        if (GlobalValue.isDebug) {
//            et_atm_amount.setText("101");
//            et_atm_phonenumber.setText("194809108");
//            et_atm_referenceno.setText("34343");
////            et_atm_nofilechosen.setText("www.google.com");
//        }

        boolean b = false;

        float amount = StringUtils.parseFloat(et_atm_amount.getText().toString().trim());
        if (amount < CacheHelper.loadCreditMinByLocal().getAtm_onlineBanking_minimum_valueF()) {
            tv_atm_amount_error.setVisibility(View.VISIBLE);
            b = true;
        }
        String phone = et_atm_phonenumber.getText().toString().trim();
        if (TextUtils.isEmpty(phone)) {
            tv_atm_phonenumber_error.setVisibility(View.VISIBLE);
            b = true;
        }
        if (bankAdapter.getSelectItem() == null) {
            b = true;
            tv_atm_selectbank_error.setVisibility(View.VISIBLE);
        }

        String referenceno = et_atm_referenceno.getText().toString().trim();
        if (TextUtils.isEmpty(referenceno)) {
            tv_atm_referenceno_error.setVisibility(View.VISIBLE);
            b = true;
        }
        String issue_date = "";
        if (getSelectDate() != null) {
            issue_date = WTimeUtils.getDateFormatter(getSelectDate(), WTimeUtils.text_yyyy_MM_dd_HH_mm_ss);
        } else {
            if (yearDate == null) {
                tv_atm_year_error.setVisibility(View.VISIBLE);
                b = true;
            }
            if (hourDate == null) {
                tv_atm_hour_error.setVisibility(View.VISIBLE);
                b = true;
            }
        }
        if (TextUtils.isEmpty(issue_date)) {
            b = true;
        }
        String remark = et_atm_remark.getText().toString().trim();

        String receipt_url = et_atm_nofilechosen.getText().toString().trim();
        if (TextUtils.isEmpty(receipt_url)) {
            tv_atm_nofilechosen_error.setVisibility(View.VISIBLE);
            b = true;
        }
        d("--->>>>>>>>---time:" + issue_date);
        if (b) {
            return;
        }

        Map<String, Object> map = MapHelper.newHashMap();
        map.put("member_id", UserInfo.getMemberId());
        map.put("phone", phone);
        map.put("amount", amount);
        map.put("payment_method", "ATM");
        map.put("reference_number", referenceno);
        map.put("issue_date", issue_date);
        map.put("receipt_url", receipt_url);
        map.put("description", remark + "");

        map.put("payment_bank", bankAdapter.getSelectItemText());
        map.put("gl_acc_id", bankAdapter.getSelectItem().getGl_acc_id());
        map.put("transfer_to", "null");
        map.put("transfer_from", "null");


        getPresenter().submit(map);


    }

    @Override
    protected void initEvent() {
        tv_atm_amount_error.setBindEditText(et_atm_amount);
        tv_atm_phonenumber_error.setBindEditText(et_atm_phonenumber);
        tv_atm_referenceno_error.setBindEditText(et_atm_referenceno);
        tv_atm_nofilechosen_error.setBindEditText(et_atm_nofilechosen);
        popupWindowBank.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                popupWindowBank.dismiss();
                bankAdapter.setSelectPosition(position);
                tv_atm_selectbank.setText(bankAdapter.getSelectItemText());
                tv_atm_selectbank_error.setVisibility(View.GONE);
            }
        });
    }

    @OnClick({
            R.id.bt_atm_submit,
            R.id.tv_atm_selectbank,
            R.id.bt_atm_upload,
            R.id.ll_atm_time_year,
            R.id.ll_atm_time_hour
    })
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_atm_submit:
                submit();
                break;
            case R.id.tv_atm_selectbank:
                List<BankModel> bankModels = bankAdapter.getmDatas();
                if (bankModels == null || bankModels.size() == 0) {
                    getPresenter().getToBanks();
                }
                PopupWindowHelper.showPopupWindow(popupWindowBank);
                break;
            case R.id.ll_atm_time_year: {
                InputMethodUtils.closeKeyBoard(getActivity());
                showYearDialog();
            }
            break;
            case R.id.ll_atm_time_hour: {
                InputMethodUtils.closeKeyBoard(getActivity());
                showHourDialog();
            }
            break;
            case R.id.bt_atm_upload: {
                EyeUtils.tagPermission();
                new RxPermissions(getActivity())
                        .request(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        .subscribe(aBoolean -> {
                            if (aBoolean) {
                                PictureSelector.create(AtmFragment.this)
                                        .openGallery(PictureMimeType.ofImage())
                                        .theme(R.style.picture_default_style)// 主题样式设置 具体参考 values/styles
                                        .previewImage(true)// 是否可预览图片
                                        .selectionMode(PictureConfig.SINGLE)// 多选 or 单选
                                        .compress(true)// 是否压缩
                                        .openClickSound(false)// 是否开启点击声音
                                        .maxSelectNum(1)
                                        .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code

                            } else {
                                ToastUtil.showToast(getString(R.string.perssion_fail));
                            }
                        });

            }
            break;
            default:
                break;
        }

    }

    @Override
    public void getToBanksResult(ResultModel<List<BankModel>> listResultModel) {
        if (listResultModel.isSuccess()) {
            bankAdapter.setDatas(listResultModel.getData());
        }
    }

    @Override
    public void submitResult(ResultModel resultModel) {
        if (resultModel.isSuccess()) {
            ToastUtil.showToast(resultModel.getMsg());
            EventBus.getDefault().post(new TopupEvent(resultModel));
        }
    }

    @Override
    public void getFromBanksResult(ResultModel<List<WithdrawBankModel>> listResultModel) {

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode != Activity.RESULT_OK)
            return;

        switch (requestCode) {
            case PictureConfig.CHOOSE_REQUEST: {
                // 图片选择
                List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                if (selectList != null && selectList.size() > 0) {
                    LocalMedia localMedia = selectList.get(0);
                    String path = localMedia.getCompressPath();
                    d("--->>>>>>>>---path:" + path);
                    uploadCloud(path);
                }
                break;
            }
        }
    }


    private void uploadCloud(String path) {
        if (TextUtils.isEmpty(path)) {
            return;
        }
        EyeUtils.uploadUrl((BaseAppCompatActivity) mActivity, path, uploadUrl -> {
            if (!TextUtils.isEmpty(uploadUrl)) {
                et_atm_nofilechosen.setText(uploadUrl);
                ToastUtil.showToast(getString(R.string.topup_uploadsuccess));
            } else {
                ToastUtil.showToast(getString(R.string.topup_uploadfail));
            }
        });

    }

}
